<template>
  <div class="layout">
    <div class="main-box">
      <div class="tit">生产统计展示</div>
      <div class="searcher-box">
        <div class="inp">
          <div class="inpH">开始日期</div>
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </div>
        <div class="inp">
          <div class="inpH">结束日期</div>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </div>
        <div class="inp">
          <div class="inpH">统计种类</div>
          <el-select
            v-model="type"
            placeholder="请选择统计种类"
            style="width: 220px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-button
          type="primary"
          icon="search"
          style="width: 80px"
          @click="handleSearch(type)"
        >
          查询
        </el-button>
        <el-button
          type="primary"
          icon="refresh"
          style="width: 80px"
          @click="reset"
        >
          重置
        </el-button>
      </div>
      <div class="default-box" v-if="status == 0">
        <div class="default">请选择要查看的统计数据种类</div>
      </div>

      <div class="table-box" v-else-if="status == 1">
        <div class="tot">
          总计划数：{{ plans.totalPlans }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
            plans.timeRange.startDate
          }}到{{ plans.timeRange.endDate }}
        </div>
        <div class="tw-box">
          <div id="col" style="width: 600px; height: 300px"></div>
          <el-table :data="plansTb" style="width: 40%">
            <el-table-column prop="status" label="状态" width="100" />
            <el-table-column prop="num" label="数量" width="100" />
            <el-table-column prop="percentage" label="百分比" width="100" />
          </el-table>
        </div>
        <div class="tw-box">
          <div id="pie" style="width: 500px; height: 300px"></div>
          <el-table :data="plansMd" style="width: 15%">
            <el-table-column prop="name" label="合金牌号" width="100" />
            <el-table-column prop="value" label="计划条数" width="100" />
          </el-table>
          <div id="pie1" style="width: 500px; height: 300px"></div>
        </div>
      </div>

      <div class="table-box" v-else-if="status == 3">
        <div class="tot">
          合金总产出:{{
            modelOutput.totalOutput
          }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
            modelOutput.timeRange.startDate
          }}到{{ modelOutput.timeRange.endDate }}
        </div>
        <div class="tw-box">
          <div
            id="pie4"
            style="width: 450px; height: 300px; margin-right: 60px"
          ></div>
          <el-table
            :data="tableData"
            style="width: 49%"
            :span-method="objectSpanMethod"
            show-summary
            :summary-method="getSummaries"
            :height="360"
            border
          >
            <el-table-column prop="modelName" label="合金牌号" width="100" />
            <el-table-column prop="totalOutput" label="总产出" width="100" />
            <el-table-column prop="storedQuantity" label="总入库" width="100" />
            <el-table-column prop="specification" label="规格" width="180" />
            <el-table-column prop="specOutput" label="产出量" width="100" />
            <el-table-column
              prop="storedQuantity1"
              label="入库量"
              width="100"
            />
          </el-table>
          <div id="pie5" style="width: 450px; height: 300px"></div>
        </div>
      </div>

      <div class="table-box" v-else>
        <div class="tot">
          {{ raws.timeRange.startDate }}到{{ raws.timeRange.endDate }}
        </div>
        <div class="tw-box">
          <div id="pie2" style="width: 600px; height: 300px"></div>
          <el-table :data="rawTb" style="width: 30%">
            <el-table-column prop="name" label="元素" width="100" />
            <el-table-column
              prop="probabilityBelowSafetyInWindow"
              label="库存风险率"
              width="100"
            />
            <el-table-column
              prop="averageDailyUsage"
              label="平均日用量"
              width="100"
            />
            <el-table-column prop="totalUsage" label="总用量" width="100" />
          </el-table>
        </div>
        <div id="pie3" style="width: 600px; height: 300px"></div>
      </div>

      <el-dialog
        :title="modelName"
        v-model="dialogVisible"
        :before-close="reset1"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        draggable
      >
        <div class="tw-box">
          <div id="pie6" style="width: 400px; height: 200px"></div>
          <el-table :data="specificationsTb" style="width: 50%">
            <el-table-column prop="specification" label="规格号" width="120" />
            <el-table-column prop="totalOutput" label="总产出" width="80" />
            <el-table-column prop="outputRatio" label="产出率" width="100" />
            <el-table-column prop="storedQuantity" label="总入库" width="80" />
          </el-table>
          <div id="pie7" style="width: 400px; height: 200px"></div>
        </div>
      </el-dialog>

      <div class="load" v-if="loading">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import request from "@/utils/request";
import * as echarts from "echarts";
export default defineComponent({
  setup() {
    const state = reactive({
      tableData: [],
      spanArr: [],
      dialogVisible: false,
      loading: false,
      startDate: "",
      endDate: "",
      type: "",
      options: [
        {
          value: "生产计划",
          label: "生产计划",
        },
        {
          value: "原材料使用",
          label: "原材料使用",
        },
        {
          value: "合金产量",
          label: "合金产量",
        },
      ],
      status: 0,
      plans: {}, //总
      plansTb: [
        //用于表格
        { status: "待生产", num: 0, percentage: "" },
        { status: "生产中", num: 0, percentage: "" },
        { status: "已完成", num: 0, percentage: "" },
        { status: "部分入库", num: 0, percentage: "" },
        { status: "已取消", num: 0, percentage: "" },
      ],
      plansPi: [
        //用于饼状图
        { value: 0, name: "待生产" },
        { value: 0, name: "生产中" },
        { value: 0, name: "已完成" },
        { value: 0, name: "部分入库" },
        { value: 0, name: "已取消" },
      ],
      plansMd: [], //用于饼状图
      raws: {},
      rawTb: [], //用于表格
      rawPi: [], //用于饼状图
      rawPi1: [], //用于饼状图
      modelOutput: {}, //总
      modelPi: [], //用于饼状图
      modelPi1: [],
      modelTb: [], //用于表格
      specifications: {},
      specificationsTb: [],
      specificationsPi: [],
      specificationsPi1: [],
      modelName: "",
    });
    const ret = () => {
      //刷新图数据
      state.plansMd = [];
      state.modelPi = [];
      state.modelPi1 = [];
      state.modelTb = [];
      state.rawPi = [];
      state.rawPi1 = [];
      state.rawTb = [];
      state.tableData = [];
    };
    const reset1 = () => {
      state.dialogVisible = false;
      state.specificationsPi = [];
      state.specificationsPi1 = [];
      state.specificationsTb = [];
    };
    const getCol = () => {
      nextTick(() => {
        const myChart = echarts.init(document.getElementById("col"));
        const option = {
          title: {
            text: "计划状态数",
          },
          xAxis: {
            type: "category",
            data: Object.keys(state.plans.statusCounts),
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              data: Object.values(state.plans.statusCounts),
              type: "bar",
            },
          ],
        };
        myChart.setOption(option);
      });
    };
    const getPie = () => {
      nextTick(() => {
        const myChart = echarts.init(document.getElementById("pie"));
        const option = {
          title: {
            text: "计划状态比",
          },
          series: [
            {
              type: "pie",
              data: state.plansPi,
            },
          ],
        };
        myChart.setOption(option);
      });
    };
    const getPie1 = () => {
      nextTick(() => {
        const myChart = echarts.init(document.getElementById("pie1"));
        const option = {
          title: {
            text: "合金涉及计划比",
          },
          series: [
            {
              type: "pie",
              data: state.plansMd,
            },
          ],
        };
        myChart.setOption(option);
      });
    };
    const plan = async () => {
      state.loading = true;
      try {
        const response = await request({
          method: "post",
          url: "/product/statistics/production-plan",
          data:
            state.startDate === "" && state.endDate === ""
              ? {}
              : {
                  startDate: state.startDate,
                  endDate: state.endDate,
                },
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (response.data.success) {
          ElMessage({
            showClose: true,
            message: "查询完成",
            type: "success",
          });
          state.plans = response.data.data;
          state.status = 1;
          state.loading = false;
          for (let i = 0; i < 5; i++) {
            state.plansTb[i].num =
              state.plans.statusCounts[state.plansTb[i].status];
            state.plansTb[i].percentage =
              state.plans.statusPercentage[state.plansTb[i].status];
            state.plansPi[i].value =
              state.plans.statusCounts[state.plansPi[i].name];
          }
          for (const key in state.plans.modelStats) {
            let obj = {};
            obj.value = state.plans.modelStats[key];
            obj.name = key;
            state.plansMd.push(obj);
          }
          getCol();
          getPie();
          getPie1();
        } else {
          ElMessage({
            showClose: true,
            message: response.data.errorMsg,
            type: "error",
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    };
    const getPie2 = () => {
      nextTick(() => {
        const myChart = echarts.init(document.getElementById("pie2"));
        const option = {
          title: {
            text: "原材料总用量比",
          },
          series: [
            {
              type: "pie",
              data: state.rawPi,
            },
          ],
        };
        myChart.setOption(option);
      });
    };
    const getPie3 = () => {
      nextTick(() => {
        const myChart = echarts.init(document.getElementById("pie3"));
        const option = {
          title: {
            text: "原材料平均日用量比",
          },
          series: [
            {
              type: "pie",
              data: state.rawPi1,
            },
          ],
        };
        myChart.setOption(option);
      });
    };
    const raw = async () => {
      state.loading = true;
      try {
        const response = await request({
          method: "post",
          url: "/product/statistics/material-usage",
          data:
            state.startDate === "" && state.endDate === ""
              ? {}
              : {
                  startDate: state.startDate,
                  endDate: state.endDate,
                },
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (response.data.success) {
          ElMessage({
            showClose: true,
            message: "查询完成",
            type: "success",
          });
          state.raws = response.data.data;
          state.status = 2;
          state.loading = false;
          for (const key in state.raws.materials) {
            let obj = {};
            let obj1 = {};
            let obj2 = {};
            obj.value = state.raws.materials[key].totalUsage;
            obj.name = key;
            obj1.value = state.raws.materials[key].averageDailyUsage;
            obj1.name = key;
            obj2 = state.raws.materials[key];
            obj2.name = key;
            state.rawPi.push(obj);
            state.rawPi1.push(obj1);
            state.rawTb.push(obj2);
          }
          getPie2();
          getPie3();
        } else {
          ElMessage({
            showClose: true,
            message: response.data.errorMsg,
            type: "error",
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    };
    const getPie4 = () => {
      nextTick(() => {
        const myChart = echarts.init(document.getElementById("pie4"));
        const option = {
          title: {
            text: "合金总产出",
          },
          series: [
            {
              type: "pie",
              data: state.modelPi,
            },
          ],
        };
        myChart.setOption(option);
      });
    };
    const getPie5 = () => {
      nextTick(() => {
        const myChart = echarts.init(document.getElementById("pie5"));
        const option = {
          title: {
            text: "合金总入库",
          },
          series: [
            {
              type: "pie",
              data: state.modelPi1,
            },
          ],
        };
        myChart.setOption(option);
      });
    };
    const cl = (obj1) => {
      let obj = {};
      let specifications = [];
      for (const key in obj1.specifications) {
        obj = obj1.specifications[key];
        obj.specification = key;
        specifications.push(obj);
      }
      obj1.specifications = specifications;
    };
    const model = async () => {
      state.loading = true;
      try {
        const response = await request({
          method: "post",
          url: "/product/statistics/alloy-production",
          data:
            state.startDate === "" && state.endDate === ""
              ? {}
              : {
                  startDate: state.startDate,
                  endDate: state.endDate,
                },
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (response.data.success) {
          ElMessage({
            showClose: true,
            message: "查询完成",
            type: "success",
          });
          state.modelOutput = response.data.data;
          state.status = 3;
          state.loading = false;
          for (const key in state.modelOutput.models) {
            let obj = {};
            let obj1 = {};
            let obj2 = {};
            obj.value = state.modelOutput.models[key].totalOutput;
            obj.name = key;
            obj1 = state.modelOutput.models[key];
            obj1.modelName = key;
            cl(obj1);
            obj2.value = state.modelOutput.models[key].storedQuantity;
            obj2.name = key;
            state.modelPi.push(obj);
            state.modelTb.push(obj1);
            state.modelPi1.push(obj2);
          }
          getPie4();
          getPie5();
          formatData();
        } else {
          ElMessage({
            showClose: true,
            message: response.data.errorMsg,
            type: "error",
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
      }
    };
    const handleSearch = async (type) => {
      if (type === "")
        ElMessage({
          showClose: true,
          message: "请选择您要查看的统计种类",
          type: "warning",
        });
      else {
        switch (type) {
          case "生产计划":
            ret();
            plan();
            break;
          case "原材料使用":
            ret();
            raw();
            break;
          case "合金产量":
            ret();
            model();
            break;
        }
      }
    };
    const reset = () => {
      state.startDate = "";
      state.endDate = "";
    };
    const formatData = () => {
      state.modelTb.forEach((item) => {
        // 计算每个型号需要合并的行数
        const rowCount = Math.max(item.specifications.length, 1);
        state.spanArr.push(rowCount);
        if (item.specifications.length > 0) {
          item.specifications.forEach((spec, index) => {
            state.tableData.push({
              modelName: index === 0 ? item.modelName : "", // 只有第一行显示型号名
              totalOutput: index === 0 ? item.totalOutput : "", // 只有第一行显示总产出
              storedQuantity: index === 0 ? item.storedQuantity : "", // 只有第一行显示总产出
              specification: spec.specification,
              specOutput: spec.totalOutput,
              storedQuantity1: spec.storedQuantity,
            });
          });
        } else {
          // 没有规格的情况，添加一行空数据
          state.tableData.push({
            modelName: item.modelName,
            totalOutput: item.totalOutput,
            storedQuantity: item.storedQuantity,
            specification: "无数据",
            specOutput: 0,
            storedQuantity1: 0,
          });
        }
      });
    };
    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
        // 计算当前行属于哪个型号
        let modelIndex = 0;
        let rowCount = 0;
        for (let i = 0; i < state.spanArr.length; i++) {
          rowCount += state.spanArr[i];
          if (rowIndex < rowCount) {
            modelIndex = i;
            break;
          }
        }
        // 计算当前型号的起始行
        const startRow = state.spanArr
          .slice(0, modelIndex)
          .reduce((a, b) => a + b, 0);

        if (rowIndex === startRow) {
          return {
            rowspan: state.spanArr[modelIndex],
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    };
    const getSummaries = (param) => {
      const { columns } = param;
      const sums = [];
      const totalOutputSum = state.modelTb.reduce(
        (sum, item) => sum + item.totalOutput,
        0
      );
      const specOutputSum = state.modelTb.reduce(
        (sum, item) => sum + Number(item.storedQuantity),
        0
      );
      const specOutputSum1 = state.modelTb.reduce(
        (sum, item) =>
          sum +
          item.specifications.reduce((s, spec) => s + spec.totalOutput, 0),
        0
      );
      const specOutputSum2 = state.modelTb.reduce(
        (sum, item) =>
          sum +
          item.specifications.reduce((s, spec) => s + spec.storedQuantity, 0),
        0
      );
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        if (column.property === "totalOutput") {
          sums[index] = totalOutputSum.toFixed(2);
        } else if (column.property === "storedQuantity") {
          sums[index] = specOutputSum.toFixed(2);
        } else if (column.property === "specOutput") {
          sums[index] = specOutputSum1.toFixed(2);
        } else if (column.property === "storedQuantity1") {
          sums[index] = specOutputSum2.toFixed(2);
        } else {
          sums[index] = "N/A";
        }
      });
      return sums;
    };
    onMounted(() => {
      state.type = "合金产量";
      handleSearch(state.type);
    });
    return {
      ...toRefs(state),
      handleSearch,
      objectSpanMethod,
      getSummaries,
      reset,
      reset1,
    };
  },
});
</script>


<style scoped>
.layout {
  width: 100%;
  height: 100%;
  background-color: #f5f6f9;
  padding-top: 20px;
}
.main-box {
  width: 98%;
  min-height: 800px;
  height: auto;
  background-color: #ffffff;
  margin: auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.tit {
  height: 40px;
  line-height: 40px;
  font-weight: 600;
  font-size: 20px;
  text-indent: 1em;
}
.searcher-box {
  margin-top: 20px;
  height: 100px;
  width: 96%;
  margin-left: auto;
  margin-right: auto;
  display: flex;
}
.inp {
  height: 50px;
  width: 30%;
  display: flex;
  overflow: hidden;
  line-height: 30px;
}
.inpH {
  width: 20%;
  margin-left: 5px;
  margin-right: 5px;
  text-align: center;
}
.default-box {
  margin: 0 20px;
  height: 300px;
}
.default {
  margin: 100px auto;
  height: 70px;
  line-height: 70px;
  font-size: 30px;
  text-align: center;
}
.table-box {
  flex: 1;
  margin: 0 20px;
  min-height: 300px;
  border: 1px black solid;
  overflow-y: auto;
  max-height: 68vh;
}
.tot {
  background-color: grey;
  color: white;
  width: 35%;
  height: 30px;
  line-height: 30px;
  font-size: 17px;
  border-radius: 5px;
  text-indent: 1em;
  margin-bottom: 10px;
}
.tw-box {
  display: flex;
  flex-wrap: wrap;
}
.load {
  position: absolute;
  top: 450px;
  left: 800px;
  width: 40px;
  height: 40px;
  border-radius: 5px;
  color: white;
  background-color: rgba(0, 0, 0, 0.68);
  line-height: 40px;
  text-align: center;
  z-index: 9999;
}
.el-icon.is-loading {
  animation: rotating 2s linear infinite;
}
@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>